package com.yb.module.db.service.impl;

import java.io.ByteArrayOutputStream;
import java.util.List;
import java.util.Map;
import java.util.zip.ZipOutputStream;

import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.yb.framework.core.utils.StringUtil;
import com.yb.module.db.domain.DbColumn;
import com.yb.module.db.domain.DbTable;
import com.yb.module.db.mapper.DbTableMapper;
import com.yb.module.db.service.DbColumnService;
import com.yb.module.db.service.DbTableService;
import com.yb.module.db.utils.GenUtil;

@Service
public class DbTableServiceImpl implements DbTableService {
	
	@Autowired
	private DbTableMapper tableMapper;
	@Autowired
	private DbColumnService columnService;
	@Autowired
	private GenUtil genUtil;
	
	@Override
	public List<DbTable> getDbList() {
		// TODO Auto-generated method stub
		return tableMapper.getDbList();
	}
	@Override
	public List<DbTable> getTableList(DbTable table) {
		// TODO Auto-generated method stub
		return tableMapper.getTableList(table);
	}
	
	@Override
	public DbTable getTableDetails(DbTable table) {
		// TODO Auto-generated method stub
		return tableMapper.getTableDetails(table);
	}
	
	@Override
	public List<String> getDataColumns(DbTable table) {
		// TODO Auto-generated method stub
		return tableMapper.getDataColumns(table);
	}
	
	@Override
	public List<Map<String, Object>> getDataRecords(DbTable table) {
		// TODO Auto-generated method stub
		return tableMapper.getDataRecords(table);
	}
	
	@Override
	public void createTable(DbTable table) {
		// TODO Auto-generated method stub
		tableMapper.createTable(table);
	}

	@Override
	public void alterTable(DbTable table) {
		// TODO Auto-generated method stub
		if (!table.getTableNameOld().equals(table.getTableNameNew())) {
			tableMapper.alterTableName(table);
		}
		if (StringUtil.isNotEmpty(table.getTableComment())) {
			tableMapper.alterTableComment(table);
		}
	}
	@Override
	public void dropTables(String dbName, String[] tableNames) {
		// TODO Auto-generated method stub
		for(String tableName : tableNames){
			DbTable table = new DbTable();
			table.setDbName(dbName);
			table.setTableName(tableName);
			tableMapper.dropTable(table);
		}
	}
	
	/**
	 * 代码生成
	 */
	@Override
	public byte[] generatorCode(String dbName, String[] tableNames) {
		ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        ZipOutputStream zip = new ZipOutputStream(outputStream);
        for (String tableName : tableNames) {
            // 查询表信息
        	DbTable table = tableMapper.getTableDetails(new DbTable(dbName, tableName));
            // 查询列信息
            List<DbColumn> columns = columnService.getColumnList(new DbColumn(dbName, tableName));
            // 生成代码
            genUtil.generatorCode(table, columns, zip);
        }
        IOUtils.closeQuietly(zip);
        return outputStream.toByteArray();
	}
}
